<template>
  <div>
    <MatchGround v-if="$store.state.pk.status === 'matching'"/>
    <PlayGround v-if="$store.state.pk.status === 'playing'"/>
  </div>
</template>

<script>
import PlayGround from "@/components/PlayGround.vue"
import MatchGround from "@/components/MatchGround.vue"
import {useStore} from "vuex"
import {onMounted,onUnmounted} from "vue"
import {GamePiece} from "@/assets/scripts/GamePiece"
export default {
  components:{
    PlayGround,
    MatchGround
  },
  setup(){
    const store = useStore();
    let socket = null;
    let socketUrl = `ws://127.0.0.1:3000/websocket/${store.state.user.token}/`;
    //开始之前先清空一下状态
    store.commit("updateLoser","none");
    store.commit("updateIsRecord",false);
    
    store.commit("updateOpponent",{
      username:"我的对手",
      photo:"https://cdn.acwing.com/media/article/image/2022/08/09/1_1db2488f17-anonymous.png",
    });
    socket = new WebSocket(socketUrl);

    onMounted(() =>{
      socket.onopen = ()=>{
        console.log("Connected!");
        store.commit("updateSocket",socket);
      },
      
      socket.onmessage = (msg) =>{
        const data = JSON.parse(msg.data);
        if(data.event === "start-matching"){
          store.commit("updateOpponent",{
            username:data.opponent_username,
            photo:data.opponent_photo
          });
          //setInterval(()=>{
          //   store.commit("updateStatus","playing");
          //   console.log('这个会一直执行，直到这个id被销毁');
          // },200);
          setTimeout( ()=>{ 
              store.commit("updateStatus","playing");
          },200)
          store.commit("updateGame",data.game);

        }else if(data.event === "move"){
          const game = store.state.pk.gameObject;
          if(data.currentPlayer === "1"){
            new GamePiece({id:store.state.user.id,c:data.col,r:data.row,color:"#000000"},game);
            store.commit("updatePlayer","2");
          }else{
            new GamePiece({id:store.state.user.id,c:data.col,r:data.row,color:"#FFFFFF"},game);
            store.commit("updatePlayer","1");
          }
          
        }else if(data.event === "result"){
          console.log(data);//这个后端传来游戏结束，设置游戏状态，并且弹出提示框
          store.commit("updateLoser",data.loser)
            store.commit("updatePlayer","1"); //不管谁赢，设置初始状态
        }
      }
    });
    onUnmounted( () =>{
        socket.close(); //断开链接
    })
  }
}
</script>

<style>

</style>
